import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Tree, message, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
import { getDepartments, createDepartment, updateDepartment, deleteDepartment } from '../../services/api';

const { Option } = Select;
const { TreeNode } = Tree;

const DepartmentConfig = () => {
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentDepartment, setCurrentDepartment] = useState({});
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);

  useEffect(() => {
    fetchDepartments();
  }, []);

  const fetchDepartments = async () => {
    setLoading(true);
    try {
      const data = await getDepartments();
      setDepartments(data);
      const formattedTreeData = formatTreeData(data);
      setTreeData(formattedTreeData);
      // 默认展开所有节点
      const allKeys = getAllNodeKeys(formattedTreeData);
      setExpandedKeys(allKeys);
    } catch (error) {
      message.error('获取部门列表失败');
      console.error('Failed to fetch departments:', error);
    }
    setLoading(false);
  };

  // 格式化部门数据为树结构
  const formatTreeData = (data, parentId = 0) => {
    return data
      .filter(item => item.parentId === parentId)
      .map(item => {
        const children = formatTreeData(data, item.id);
        return {
          title: item.name,
          key: item.id,
          ...item,
          children: children.length > 0 ? children : undefined
        };
      });
  };

  // 获取所有节点的key
  const getAllNodeKeys = (data) => {
    let keys = [];
    data.forEach(node => {
      keys.push(node.key);
      if (node.children) {
        keys = keys.concat(getAllNodeKeys(node.children));
      }
    });
    return keys;
  };

  const handleAdd = () => {
    setEditMode(false);
    setCurrentDepartment({});
    form.resetFields();
    setVisible(true);
  };

  const handleEdit = (department) => {
    setEditMode(true);
    setCurrentDepartment(department);
    form.setFieldsValue(department);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteDepartment(id);
      message.success('删除部门成功');
      fetchDepartments();
    } catch (error) {
      message.error('删除部门失败');
      console.error('Failed to delete department:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      if (editMode) {
        await updateDepartment(currentDepartment.id, values);
        message.success('更新部门成功');
      } else {
        await createDepartment(values);
        message.success('创建部门成功');
      }
      setVisible(false);
      fetchDepartments();
    } catch (error) {
      message.error(editMode ? '更新部门失败' : '创建部门失败');
      console.error('Failed to submit department:', error);
    }
  };

  // 递归渲染树节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} dataRef={item} />;
    });

  const filteredDepartments = departments.filter(dept =>
    dept.name.toLowerCase().includes(searchText.toLowerCase()) ||
    dept.description.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '部门名称', dataIndex: 'name', key: 'name' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    { title: '父部门', dataIndex: 'parentId', key: 'parentId', render: (parentId) => {
      if (parentId === 0) return '无';
      const parentDept = departments.find(dept => dept.id === parentId);
      return parentDept ? parentDept.name : '未知';
    }},
    { title: '负责人', dataIndex: 'manager', key: 'manager', render: manager => manager?.username || '-'},
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'active' ? 'green' : 'red' }}>
        {status === 'active' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          style={{ marginRight: 8 }}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </div>
    )}
  ];

  // 获取所有父部门选项（排除当前部门及其子部门）
  const getParentDepartmentOptions = () => {
    const excludeIds = editMode ? getAllNodeKeys(formatTreeData([currentDepartment])) : [];
    return [
      <Option key={0} value={0}>无</Option>,
      ...departments
        .filter(dept => !excludeIds.includes(dept.id))
        .map(dept => (
          <Option key={dept.id} value={dept.id}>{dept.name}</Option>
        ))
    ];
  };

  return (
    <div className="department-config">
      <div className="header">
        <h2>部门配置</h2>
        <div className="search-bar">
          <Input
            placeholder="搜索部门名称或描述"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增部门
          </Button>
        </div>
      </div>

      <div className="department-tree">
        <h3><TeamOutlined /> 部门结构</h3>
        <Tree
          showLine
          defaultExpandAll
          expandedKeys={expandedKeys}
          onExpand={keys => setExpandedKeys(keys)}
          onSelect={([selectedKey]) => {
            const selectedDept = departments.find(dept => dept.id === Number(selectedKey));
            if (selectedDept) handleEdit(selectedDept);
          }}
        >
          {renderTreeNodes(treeData)}
        </Tree>
      </div>

      <Divider />

      <Table
        columns={columns}
        dataSource={filteredDepartments}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editMode ? '编辑部门' : '新增部门'}
        visible={visible}
        onOk={form.submit}
        onCancel={() => setVisible(false)}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder="请输入部门名称" />
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入部门描述" />
          </Form.Item>

          <Form.Item name="parentId" label="父部门">
            <Select placeholder="请选择父部门">
              {getParentDepartmentOptions()}
            </Select>
          </Form.Item>

          <Form.Item name="managerId" label="负责人">
            <Select placeholder="请选择负责人">
              {/* 这里需要动态加载用户数据 */}
              <Option value={1}>管理员</Option>
              <Option value={2}>张三</Option>
              <Option value={3}>李四</Option>
            </Select>
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentConfig;